<!--投融资板块-->
<template>
  <a-layout>
    <a-layout-header>
      <a-range-picker
        v-model:value="value4"
        picker="month"
        @change="panelChange"
        :placeholder="['开始日期', '结束日期']"
      />
    </a-layout-header>
    <a-layout-content>
      <a-row>
        <a-col :span="12" class="trztable">
          <a-table
            :dataSource="basicData"
            :columns="basicColumns"
            :pagination="false"
          />
        </a-col>
        <a-col :span="12">
          <a-card :title="融资成本" :bordered="false">
            <div class="echart-pic">
              <div class="about main" id="main1"></div>
            </div>
          </a-card>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-card :title="融资成本" :bordered="false">
            <div class="echart-pic">
              <div class="about main" id="main2"></div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card :title="还本" :bordered="false">
            <div class="echart-pic">
              <div class="about main" id="main3"></div>
            </div>
          </a-card>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="12">
          <a-card :title="付息" :bordered="false">
            <div class="echart-pic">
              <div class="about main" id="main4"></div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card :title="本息合计" :bordered="false">
            <div class="echart-pic">
              <div class="about main" id="main5"></div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </a-layout-content>
  </a-layout>
</template>
<script>
import { request } from "../../utils/request";
import { DownOutlined } from "@ant-design/icons-vue";
import * as echarts from "echarts";

const value4 = "";
const startDate = "";
const endDate = "";

const Loan = 0; //贷款余额
const Repayment = 0; //还本
const pay = 0; //付息

const xmList = []; //项目名称
const XIRR = [];
const baseData = []; // 所有数据项目+还款
const monthCollection = [
  "01",
  "02",
  "03",
  "04",
  "05",
  "06",
  "07",
  "08",
  "09",
  "10",
  "11",
  "12",
];
let allYearMonth = []; //前一年，后一年

const basicColumns = [
  {
    title: "指标",
    dataIndex: "indicators",
    key: "indicators",
  },
  {
    title: "额度（元）",
    dataIndex: "current",
    key: "current",
  },
];
const basicData = [];
export default {
  data() {
    return {
      basicColumns,
      basicData,
      value4,
      startDate,
      endDate,
      Loan,
      Repayment,
      pay,
      xmList,
      XIRR,
      baseData,
      echar1Loading: true,
      echar2Loading: true,
    };
  },
  mounted() {
    this.getXMDatas();
    this.getDatas();
    this.init();
    this.getBashDatas();
  },
  methods: {
    init() {
      this.echart2();
    },
    getDatas() {
      this.basicData = [];
      this.Loan = 0;
      this.Repayment = 0;
      this.pay = 0;
      request({
        url: `/api/trz/hklist?startDate=${this.startDate}&endDate=${this.endDate}`,
        method: "get",
      }).then((res) => {
        res.forEach((v) => {
          this.Loan += Number(v.hked); //贷款余额
          if (Number(v.hked) > 0) {
            //还本
            this.Repayment += Number(v.hked);
          }
          this.pay += Number(v.fx); //付息
        });
        this.Loan = Math.abs(this.Loan); //贷款余额取正
        // this.basicData.push({
        //   key: "1",
        //   indicators: "贷款余额",
        //   current: this.Loan.toFixed(2),
        // });
        this.basicData.push({
          key: "2",
          indicators: "还本",
          current: this.Repayment.toFixed(2),
        });
        this.basicData.push({
          key: "3",
          indicators: "付息",
          current: this.pay.toFixed(2),
        });
      });
    },
    getXMDatas() {
      this.xmList = [];
      this.XIRR = [];
      request({
        url: `/api/trz/xmlist`,
        method: "get",
      }).then((res) => {
        res.forEach((v) => {
          this.xmList.push(v.xmmc);
          this.XIRR.push(v.xirr);
          this.echart1();
        });
      });
    },
    getBashDatas() {
      //获取所有项目+还款信息
      request({
        url: `/api/trz/list`,
        method: "get",
      }).then((res) => {
        this.baseData = res;
        this.getDateRange();
      });
    },
    panelChange(value, mode) {
      this.startDate = mode[0];
      this.endDate = mode[1];
      this.getDatas();
    },
    search() {},

    echart1() {
      // 基于准备好的dom，初始化echarts实例
      var myChart1 = this.$echarts.init(document.getElementById("main1"));
      // myChart1.showLoading();
      // 绘制图表
      myChart1.setOption({
        title: { text: "融资成本" },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
            label: {
              show: true,
            },
          },
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        calculable: true,
        grid: {
          top: "20%",
          left: "5%",
          right: "10%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: this.xmList,
            axisLabel: {
              interval: 0, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
              rotate: 38, //调整数值改变倾斜的幅度（范围-90到90）
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "XIRR（%）",
          },
        ],
        dataZoom: [
          {
            show: true,
            start: 0,
            end: 100,
          },
          {
            type: "inside",
            start: 0,
            end: 100,
          },
        ],
        series: [
          {
            type: "bar",
            data: this.XIRR,
          },
        ],
      });
    },
    echart2(rzjg) {
      // 基于准备好的dom，初始化echarts实例
      var myChart2 = this.$echarts.init(document.getElementById("main2"));
      // 绘制图表
      myChart2.setOption({
        title: {
          text: "融资结构",
          left: "center",
        },
        tooltip: {
          trigger: "item",
        },
        legend: {
          orient: "vertical",
          left: "left",
        },
        series: [
          {
            type: "pie",
            radius: "50%",
            data: rzjg,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              normal: {
                show: true,
                position: "outer", // 数值显示在内部
                formatter: "{b}:{d}%", // 格式化数值百分比输出
              },
            },
          },
        ],
      });
    },
    echart3(a, b) {
      // 基于准备好的dom，初始化echarts实例
      var myChart3 = this.$echarts.init(document.getElementById("main3"));
      // 绘制图表
      myChart3.setOption({
        title: { text: "还本" },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
            label: {
              show: true,
            },
          },
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },

            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        calculable: true,
        grid: {
          top: "20%",
          left: "5%",
          right: "10%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: a,
            axisLabel: {
              interval: 0, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
              rotate: 38, //调整数值改变倾斜的幅度（范围-90到90）
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "元",
          },
        ],
        dataZoom: [
          {
            show: true,
            start: 0,
            end: 100,
          },
          {
            type: "inside",
            start: 0,
            end: 100,
          },
        ],
        series: [
          {
            type: "bar",
            data: b,
          },
        ],
      });
    },
    echart4(a, b) {
      // 基于准备好的dom，初始化echarts实例
      var myChart4 = this.$echarts.init(document.getElementById("main4"));
      // 绘制图表
      myChart4.setOption({
        title: { text: "付息" },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
            label: {
              show: true,
            },
          },
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        calculable: true,
        grid: {
          top: "20%",
          left: "5%",
          right: "10%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: a,
            axisLabel: {
              interval: 0, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
              rotate: 38, //调整数值改变倾斜的幅度（范围-90到90）
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "元",
          },
        ],
        dataZoom: [
          {
            show: true,
            start: 0,
            end: 100,
          },
          {
            type: "inside",
            start: 0,
            end: 100,
          },
        ],
        series: [
          {
            type: "bar",
            data: b,
          },
        ],
      });
    },
    echart5(a, b) {
      // 基于准备好的dom，初始化echarts实例
      var myChart5 = this.$echarts.init(document.getElementById("main5"));
      // 绘制图表
      myChart5.setOption({
        title: { text: "本息合计" },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
            label: {
              show: true,
            },
          },
        },
        toolbox: {
          show: true,
          feature: {
            mark: { show: true },
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        calculable: true,
        grid: {
          top: "20%",
          left: "5%",
          right: "10%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: a,
            axisLabel: {
              interval: 0, //坐标刻度之间的显示间隔，默认就可以了（默认是不重叠）
              rotate: 38, //调整数值改变倾斜的幅度（范围-90到90）
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "元",
          },
        ],
        dataZoom: [
          {
            show: true,
            start: 0,
            end: 100,
          },
          {
            type: "inside",
            start: 0,
            end: 100,
          },
        ],
        series: [
          {
            type: "bar",
            data: b,
          },
        ],
      });
    },
    // 获取当前年份 (配合还本、付息、本息合计前一年 后一年)
    getDateRange() {
      var date = new Date();
      var nowYear = date.getFullYear();
      var rangeStartYear = Number(nowYear - 1);
      var rangeEndYear = Number(nowYear + 1);
      var nowMonth = date.getMonth() + 1;
      allYearMonth = [];
      if (nowMonth >= 1 && nowMonth <= 9) {
        nowMonth = "0" + nowMonth;
      }
      nowMonth = nowMonth + "";
      var i = monthCollection.indexOf(nowMonth);
      //前一年
      for (var x = i; x < monthCollection.length; x++) {
        allYearMonth.push(rangeStartYear + "-" + monthCollection[x]);
      }
      // 今年
      for (var y = 0; y < monthCollection.length; y++) {
        allYearMonth.push(nowYear + "-" + monthCollection[y]);
      }
      // 后一年
      for (var m = 0; m <= i; m++) {
        allYearMonth.push(rangeEndYear + "-" + monthCollection[m]);
      }
      var hbValue = {}; //还本
      var fxValue = {}; //还息
      var bxValue = {}; //本息合计
      var rzjg = []; // echart饼图所需数据格式
      var yhjk = { 银行: 0 };
      var qyjk = { 企业: 0 };
      var zljk = { 租赁公司: 0 };
      var nowData = new Date(); //今天
      var nowDataTime = nowData.getTime(); //毫秒
      this.baseData.forEach((v) => {
        //融资结构统计
        if (v.ywlx2 == 0 || v.ywlx2 == 1) {
          v.trzhklist.forEach((c) => {
            if (c.hksj) {
              if (new Date(c.hksj).getTime() < nowDataTime) {
                yhjk["银行"] += Number(c.hked);
              }
            }
          });
        }
        if (v.ywlx2 == 2) {
          v.trzhklist.forEach((c) => {
            if (c.hksj) {
              if (new Date(c.hksj).getTime() < nowDataTime) {
                qyjk["企业"] += Number(c.hked);
              }
            }
          });
        }
        if (v.ywlx2 == 3 || v.ywlx2 == 4) {
          v.trzhklist.forEach((c) => {
            if (c.hksj) {
              if (new Date(c.hksj).getTime() < nowDataTime) {
                zljk["租赁公司"] += Number(c.hked);
              }
            }
          });
        }
        //本息合计统计
        v.trzhklist.forEach((a) => {
          allYearMonth.forEach((b) => {
            if (a.hksj) {
              if (a.hksj.substring(0, 7) == b) {
                if (Number(a.hked) > 0) {
                  //还本
                  hbValue[b] =
                    (hbValue[b] == undefined ? 0 : hbValue[b]) + Number(a.hked);
                }
                if (Number(a.fx) > 0) {
                  //付息
                  fxValue[b] =
                    (fxValue[b] == undefined ? 0 : fxValue[b]) + Number(a.fx);
                }
                if (Number(a.bxhj) > 0) {
                  //本息合计
                  bxValue[b] =
                    (bxValue[b] == undefined ? 0 : bxValue[b]) + Number(a.bxhj);
                }
              }
            }
          });
        });
      });

      // console.log(hbValue);
      var yhPercent =
        (Math.abs(yhjk["银行"]) /
          (Math.abs(yhjk["银行"]) +
            Math.abs(qyjk["企业"]) +
            Math.abs(zljk["租赁公司"]))) *
        100;
      var qyPercent =
        (Math.abs(qyjk["企业"]) /
          (Math.abs(yhjk["银行"]) +
            Math.abs(qyjk["企业"]) +
            Math.abs(zljk["租赁公司"]))) *
        100;
      var zlPercent =
        (Math.abs(zljk["租赁公司"]) /
          (Math.abs(yhjk["银行"]) +
            Math.abs(qyjk["企业"]) +
            Math.abs(zljk["租赁公司"]))) *
        100;
      rzjg.push({ name: "银行", value: yhPercent.toFixed(2) });
      rzjg.push({ name: "企业", value: qyPercent.toFixed(2) });
      rzjg.push({ name: "租赁公司", value: zlPercent.toFixed(2) });
      allYearMonth.forEach((p) => {
        if (hbValue[p]) {
        } else {
          hbValue[p] = 0;
        }
        if (fxValue[p]) {
        } else {
          fxValue[p] = 0;
        }
        if (bxValue[p]) {
        } else {
          bxValue[p] = 0;
        }
      });
     
      var hbArr = [];
      var fxArr = [];
      var bxArr = [];

      allYearMonth.forEach((v1) => {
        hbArr.push(hbValue[v1]);
      });
      allYearMonth.forEach((v1) => {
        fxArr.push(fxValue[v1]);
      });
      allYearMonth.forEach((v1) => {
        bxArr.push(bxValue[v1]);
      });

      this.echart2(rzjg);
      this.echart3(allYearMonth, hbArr);
      this.echart4(allYearMonth, fxArr);
      this.echart5(allYearMonth, bxArr);
    },
  },
  components: {
    DownOutlined,
  },
};
</script>
<style scoped>
:deep(.ant-dropdown-button) {
  margin-right: 8px;
  margin-bottom: 8px;
}
.ant-dropdown-menu {
  height: 150px;
  overflow: auto;
}
.gutter-example >>> .ant-row > div {
  background: transparent;
  border: 0;
}
.gutter-box {
  padding: 5px 0;
}
.main {
  height: 400px;
  width: 100%;
}
.echart-pic {
  height: 400px;
  width: 100%;
  line-height: 400px;
  text-align: center;
  overflow: hidden;
}
.mycard .ant-col {
  margin-bottom: 10px;
}
/deep/ .ant-table-row-cell-break-word {
  text-align: center;
}
/deep/ .rowcolor {
  background: #daeef3;
}
/deep/ .ant-layout-header {
  background: none;
}
/deep/ .ant-col.ant-col-12.trztable {
  background: #fff;
}
</style>